package com.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zuul.constant.CheckConstant;
import lombok.SneakyThrows;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * @author yinxing
 * @date 2022-08-05
 */
@Component
public class ZuulFilterComponent extends ZuulFilter {
    /**
     * 配置为前置过滤器
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        //校验请求头中有没有携带信息
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getHeader("yx-token");
        if (token == null || token.equals("")) {
            //响应code
            requestContext.setResponseStatusCode(401);
            //拦截请求
            requestContext.setSendZuulResponse(false);
            Entity response = Entity.builder().code(402).data(null).message(CheckConstant.NOT_HAVE_PERMISSION).build();
            requestContext.getResponse().setContentType("text/json;charset=UTF-8");
            requestContext.getResponse().getWriter().write(JSONObject.toJSONString(response));
        }
        return null;
    }
}
